//
// Created by DengLibin on 2019/1/3 0003.
//
/**
 * 互斥锁
 */
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; //互斥锁

int share_i = 0; //共享变量

void increase_i();

int main13()
{
    pthread_t t1;
    pthread_t t2;
    pthread_create(&t1, NULL, (void * (*)(void *))increase_i, NULL);
    pthread_create(&t2, NULL, (void * (*)(void *))increase_i, NULL);

    pthread_join(t1, NULL);
    pthread_join(t2, NULL);

    printf("share_i = %d\n", share_i);
    return 0;
}
void increase_i()
{
    //加锁
    if (pthread_mutex_lock(&mutex) != 0)
    {
        printf("加锁失败");
        exit(EXIT_FAILURE);
    }
    for (int i = 0; i < 100000; i++)
    {
        share_i++;
    }

    //解锁
    if (pthread_mutex_unlock(&mutex) != 0)
    {
        printf("解锁失败");
        exit(EXIT_FAILURE);
    }
}
